import Vue from "vue";
import Router from "vue-router";
import Login from "@/components/Login";
import User from "@/components/User";
import ShowName from "@/components/ShowName";
import Home from "@/components/Home";

Vue.use(Router);

const router = new Router({
  routes: [
    {
      path: "/",
      redirect: "login"
    },
    {
      path: "/login",
      name: "Login",
      component: Login
    },
    {
      path: "/home",
      component: Home,
      children: [
        {
          path: "/",
          redirect: "/user"
        },
        {
          path: "/user",
          name: "User",
          component: User
        },
        {
          path: "/showname",
          name: "ShowName",
          component: ShowName
        }
      ]
    }
  ]
});

// 挂在路由导航守卫
router.beforeEach((to, from, next) => {
  if (to.path === "/login") return next();
  const tokenStr = localStorage.getItem("token");
  if (!tokenStr) return next("/login"); //返回login页面
  next(); //进入home页面
});

export default router;
